package com.wanyang.service;

import com.wanyang.bo.LevelBO;
import com.wanyang.dao.MemberDao;
import com.wanyang.mapper.MemberDOMapper;
import com.wanyang.vo.LevelTopVO;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;

@Service
public class LevelExperienceServiceImpl implements LevelExperienceService {

    BigDecimal base = new BigDecimal(18);

    @Resource
    private MemberDOMapper memberDOMapper;

    @Resource
    private MemberDao memberDao;

    @Override
    public BigDecimal getLevelExperience(Integer level) {
        return new BigDecimal(level).pow(2).add(base).add(new BigDecimal(level));
    }


    @Override
    public LevelBO upgradeIfPossible(Integer oldLevel, Integer oldExperience, Integer addExperience) {
        BigDecimal currentExperience = new BigDecimal(oldExperience).add(new BigDecimal(addExperience));
        BigDecimal currentLevelExperience = getLevelExperience(oldLevel);

        if (currentExperience.compareTo(currentLevelExperience) >= 0) {
            // 目前经验值 > 目前等级经验值
            int newLevel;
            int increment = 1;

            for (;;) {
                BigDecimal levelExperience = getLevelExperience(oldLevel + increment);
                if (levelExperience.compareTo(currentExperience) >= 0) {
                    newLevel = oldLevel + increment;
                    break;
                }

                increment++;
            }

            return new LevelBO(newLevel, currentExperience.intValue());
        }

        return new LevelBO(oldLevel, currentExperience.intValue());
    }

    @Override
    public List<LevelTopVO> listTop10() {
        List<LevelTopVO> levelTopVOs = memberDao.listTop10();

        for (LevelTopVO levelTopVO : levelTopVOs) {
            if (levelTopVO.getLevel() == 1) {
                levelTopVO.setCurrentExperience(levelTopVO.getExperience());

            } else {
                BigDecimal levelExperience = getLevelExperience(levelTopVO.getLevel());
                levelTopVO.setCurrentExperience(levelTopVO.getExperience() - levelExperience.intValue());

            }

        }

        return levelTopVOs;
    }
}
